package controllers

import (
	"day3zk/cache"
	"day3zk/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"strconv"
	"time"
)

type WWW struct {
	beego.Controller
}

type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (w *WWW) Add() {
	bos := w.GetString("bos")
	nie := w.GetString("nie")
	ping := w.GetString("ping")
	zuo := w.GetString("zuo")
	if bos == "" || nie == "" || ping == "" || zuo == "" {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加字段不得为空",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	ww := models.Lyon{
		Bos:  bos,
		Nie:  nie,
		Ping: ping,
		Zuo:  zuo,
	}
	err := models.DB.Create(&ww).Error
	lyoukey := "layout_id" + strconv.Itoa(int(ww.ID))
	lyouJson, _ := json.Marshal(ww)
	cache.Rdb.Set(cache.Ctx, lyoukey, lyouJson, time.Hour*1)
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: ww,
		}
		w.ServeJSON()
	}
}

func (w *WWW) List() {
	var ww []models.Lyon
	redisKey := "redis_id"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redisKey).Result()
	if redisData == "" {
		err := models.DB.Find(&ww).Error
		if err != nil {
			w.Data["json"] = Msg{
				Code: 0,
				Msg:  "列表查询失败",
				Data: nil,
			}
			w.ServeJSON()
			return
		} else {
			w.Data["json"] = Msg{
				Code: 200,
				Msg:  "列表查询成功",
				Data: ww,
			}
			w.ServeJSON()
		}
		RedisJson, _ := json.Marshal(ww)
		cache.Rdb.Set(cache.Ctx, redisKey, RedisJson, time.Hour*1)
	} else {
		json.Unmarshal([]byte(redisKey), &ww)
	}
}

func (w *WWW) Update() {
	bos := w.GetString("bos")
	nie := w.GetString("nie")
	ping := w.GetString("ping")
	zuo := w.GetString("zuo")
	id, _ := w.GetInt("id")
	if bos == "" || nie == "" || ping == "" || zuo == "" {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加字段不得为空",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	ww := models.Lyon{
		Model: gorm.Model{
			ID: uint(id),
		},
		Bos:  bos,
		Nie:  nie,
		Ping: ping,
		Zuo:  zuo,
	}
	err := models.DB.Updates(&ww).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "修改成功",
			Data: ww,
		}
		w.ServeJSON()
	}
}
func (w *WWW) Del() {
	id, _ := w.GetInt("id")
	err := models.DB.Delete(&models.Lyon{}, id).Error
	lyoukey := "layout_id" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, lyoukey)
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		w.ServeJSON()
	}
}
